package com.milepost.messagepush.push.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.milepost.messagepush.push.entity.WorkWxMessageEntity;
import com.milepost.messagepush.push.entity.WorkWxUserEntity;
import com.milepost.messagepush.push.mapper.WorkWxMessageMapper;
import com.milepost.messagepush.push.mapper.WorkWxUserMapper;
import com.milepost.messagepush.push.service.PushService;
import com.milepost.messagepush.util.UUIDUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author huarf
 * @Description
 * @create 2022-04-05 14:35
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class PushServiceImpl implements PushService {

    private final WorkWxMessageMapper workWxMessageMapper;

    private final WorkWxUserMapper workWxUserMapper;

    @Override
    public void insertPushRecord(WorkWxMessageEntity workWxMessageEntity) {

        workWxMessageEntity.setId(UUIDUtil.randomUUID());
        workWxMessageEntity.setBeginTime(new Date());
        workWxMessageMapper.insert(workWxMessageEntity);
    }

    @Override
    public void updatePushRecord(WorkWxMessageEntity workWxMessageEntity) {

        workWxMessageEntity.setEndTime(new Date());
        workWxMessageMapper.updateById(workWxMessageEntity);
    }

    @Override
    public void getToWorkWxIds(WorkWxMessageEntity workWxMessageEntity) {

        String toUserIds = workWxMessageEntity.getToUserIds();
        if (StringUtils.isBlank(toUserIds)) {
            return;
        }

        List<String> toUserIdList = Arrays.asList(toUserIds.split("\\|"));
        if (toUserIdList.isEmpty()) {
            return;
        }

        List<WorkWxUserEntity> workWxUserEntityList = workWxUserMapper.selectList(new QueryWrapper<WorkWxUserEntity>().lambda()
                .in(WorkWxUserEntity::getUserId, toUserIdList));

        if (workWxUserEntityList.isEmpty()) {
            return;
        }

        StringBuffer workWxIdSb = new StringBuffer("");
        for (WorkWxUserEntity workWxUserEntity : workWxUserEntityList) {
            String workWxId = workWxUserEntity.getWorkWxId();
            workWxIdSb.append(workWxId).append("|");
        }
        workWxMessageEntity.setToWorkWxIds(workWxIdSb.deleteCharAt(workWxIdSb.length()-1).toString());
    }

}
